<template>
  <div class="app-container">
    <!-- 搜索区域 -->
    <el-card class="filter-container" shadow="never">
      <el-form :inline="true" :model="queryParams" @keyup.enter="handleQuery">
        <el-form-item label="科室名称">
          <el-input v-model="queryParams.name" placeholder="请输入科室名称" clearable />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="queryParams.status" placeholder="请选择状态" style="width: 150px" clearable>
            <el-option label="正常" :value="1" />
            <el-option label="停诊" :value="0" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">查询</el-button>
          <el-button @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 操作按钮区域 -->
    <el-card class="table-container" shadow="never">
      <template #header>
        <el-button type="primary" @click="handleAdd">新增科室</el-button>
      </template>

      <!-- 表格 -->
      <el-table v-loading="loading" :data="departmentList">
        <el-table-column label="科室名称" prop="name" />
        <el-table-column label="描述" prop="description" show-overflow-tooltip />
        <el-table-column label="状态" align="center">
          <template #default="scope">
            <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'">
              {{ scope.row.status === 1 ? '正常' : '停诊' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="创建时间" prop="createTime" width="180" />
        <el-table-column label="操作" width="180" align="center">
          <template #default="scope">
            <el-button type="primary" link @click="handleEdit(scope.row)">编辑</el-button>
            <el-button type="primary" link @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="queryParams.current"
          v-model:page-size="queryParams.size"
          :total="total"
          :page-sizes="[10, 20, 30, 50]"
          layout="total, sizes, prev, pager, next"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 新增/编辑弹窗 -->
    <el-dialog
      :title="dialog.title"
      v-model="dialog.visible"
      width="500px"
      @close="handleDialogClose"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="80px"
      >
        <el-form-item label="科室名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入科室名称" />
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input
            v-model="form.description"
            type="textarea"
            placeholder="请输入科室描述"
            :rows="3"
          />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio :label="1">正常</el-radio>
            <el-radio :label="0">停诊</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialog.visible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getDepartmentList, addDepartment, updateDepartment, deleteDepartment } from '@/api/department'

// 查询参数
const queryParams = reactive({
  current: 1,
  size: 10,
  name: '',
  status: ''
})

// 数据列表
const loading = ref(false)
const total = ref(0)
const departmentList = ref([])

// 表单相关
const dialog = reactive({
  visible: false,
  title: '',
  type: 'add'
})

const formRef = ref()
const form = reactive({
  id: undefined,
  name: '',
  description: '',
  status: 1
})

const rules = {
  name: [{ required: true, message: '请输入科室名称', trigger: 'blur' }],
  status: [{ required: true, message: '请选择状态', trigger: 'change' }]
}

// 获取数据列表
const getList = async () => {
  try {
    loading.value = true
    const { data } = await getDepartmentList(queryParams)
    departmentList.value = data.records
    total.value = data.total
  } catch (error) {
    console.error('获取科室列表失败:', error)
  } finally {
    loading.value = false
  }
}

// 查询操作
const handleQuery = () => {
  queryParams.current = 1
  getList()
}

// 重置查询
const resetQuery = () => {
  queryParams.name = ''
    queryParams.status = ''
  handleQuery()
}

// 新增操作
const handleAdd = () => {
  dialog.type = 'add'
  dialog.title = '新增科室'
  dialog.visible = true
  form.id = undefined
  form.name = ''
  form.description = ''
  form.status = 1
}

// 编辑操作
const handleEdit = (row) => {
  dialog.type = 'edit'
  dialog.title = '编辑科室'
  dialog.visible = true
  Object.assign(form, row)
}

// 删除操作
const handleDelete = (row) => {
  ElMessageBox.confirm('确认要删除该科室吗?', '提示', {
    type: 'warning'
  }).then(async () => {
    try {
      await deleteDepartment(row.id)
      ElMessage.success('删除成功')
      getList()
    } catch (error) {
      console.error('删除失败:', error)
    }
  }).catch(() => {})
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return

  await formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        if (dialog.type === 'add') {
          await addDepartment(form)
          ElMessage.success('新增成功')
        } else {
          await updateDepartment(form)
          ElMessage.success('更新成功')
        }
        dialog.visible = false
        getList()
      } catch (error) {
        console.error('保存失败:', error)
      }
    }
  })
}

// 弹窗关闭
const handleDialogClose = () => {
  if (formRef.value) {
    formRef.value.resetFields()
  }
}

// 分页操作
const handleSizeChange = (val) => {
  queryParams.size = val
  getList()
}

const handleCurrentChange = (val) => {
  queryParams.current = val
  getList()
}

onMounted(() => {
  getList()
})
</script>

<style lang="scss" scoped>
.app-container {
  padding: 20px;

  .filter-container {
    margin-bottom: 20px;
  }

  .table-container {
    margin-bottom: 20px;
  }

  .pagination-container {
    margin-top: 20px;
    text-align: right;
  }
}
</style>
